package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Resource
    DishService dishService;
    @Resource
    DishFlavorService dishFlavorService;
    @Resource
    CategoryService categoryService;

    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody DishDto dish){
        dishService.saveWithFlavor(dish);
        return R.success("新增菜品成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        log.info("page={},pageSize={},name={}",page,pageSize,name);

        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        if(name != null) queryWrapper.like(Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getSort);

        //执行查询
        dishService.page(pageInfo,queryWrapper);

        //我们需要返回Page中为 DisDto 对象的。 DisDto: { Dish, categoryName}
        //定义DishDto类型 的 page
        Page<DishDto> dtoPage = new Page<>();
        //将pageInfo值(除了records)复制到dtoPage; records内存着页面要展示的对象
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        //从pageInfo中获取records 但只有Dish值 无 categoryName
        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            Long categoryId  = item.getCategoryId();
            //根据id查询出分类对象
            Category category = categoryService.getById(categoryId);
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //得到categoryName
            if(category != null ){
                String na = category.getName();
                dishDto.setCategoryName(na);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);

        return R.success(dtoPage);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updatewithFalvor(dishDto);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable  Long id){
        DishDto dishDto = dishService.updateALLById(id);
        return R.success(dishDto);
    }

//    /**
//     * 根据id删除菜品
//     * @param ids
//     * @return
//     */
//    @DeleteMapping
//    public R<String> delect(Long ids){
//
//        dishService.removeWithFalvor(ids);
//        return R.success("删除成功");
//    }

    @PostMapping("/status/{value}")
    public R<String> UPstatus(Long[] ids,@PathVariable int value){

        for(Long id:ids){
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(Dish::getId,id);
            Dish dish = dishService.getOne(queryWrapper);
            dish.setStatus(dish.getStatus()^1);

            dishService.updateById(dish);
        }

        if(value==0) return R.success("起售成功");
        else return R.success("停售成功");
    }

    @DeleteMapping
    public R<String> delect(Long[] ids){

       // int len = ids.length;

        for(Long x:ids){
            dishService.removeWithFalvor(x);
        }

        return R.success("删除成功");
    }

    /**
     * 根据条件查询对应菜品数量
     * @param
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Long categoryId){
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Dish::getCategoryId,categoryId);
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加条件，查询状态为1的（起售状态）
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //条件排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lambdaQueryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL: select* from dishflavor where dish_id=?;
            List<DishFlavor> dishFlavorlist = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorlist);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }


}



